package com.hxh.usermanagementsystem;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.hxh.usermanagementsystem.util.ConstVariable;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    
    private EditText loginnameEdit; // 用户名
    private EditText passwordEdit; // 密码
    private Button loginButton; // 登录按钮

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
    }

    // 初始化组件并设置监听器
    private void init() {
        loginnameEdit = findViewById(R.id.UserNameEdit);
        passwordEdit = findViewById(R.id.PassWordEdit);
        loginButton = findViewById(R.id.LoginButton);
        loginButton.setOnClickListener(this);
    }

    // 登录按钮监听器实现
    @Override
    public void onClick(View view) {
        // 发起登录请求
        LoginTask loginTask = new LoginTask();
        loginTask.execute(ConstVariable.URL_ADDRESS + "login");
    }

    private class LoginTask extends AsyncTask<String, Void, Boolean> {

        @Override
        protected Boolean doInBackground(String... params) {
            String loginUrl = params[0];
            String loginname = loginnameEdit.getText().toString().trim(); // 用户名
            String password = passwordEdit.getText().toString().trim(); // 密码

            Log.e("loginname: ", loginname);
            Log.e("password: ", password);

            try {
                // 创建URL对象
                URL url = new URL(loginUrl);

                // 创建HttpURLConnection对象
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setDoOutput(true);

                // 构建请求参数
                String data = "loginname=" + URLEncoder.encode(loginname, "UTF-8") +
                        "&password=" + URLEncoder.encode(password, "UTF-8");

                // 发送请求参数
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(data.getBytes());
                outputStream.flush();
                outputStream.close();

                // 获取响应数据
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = connection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        response.append(line);
                    }
                    bufferedReader.close();
                    inputStream.close();

                    // 解析响应数据
                    Log.e("响应: ", response.toString());
                    JSONObject jsonResponse = new JSONObject(response.toString());
                    boolean success = jsonResponse.getBoolean("data");
                    return success;
                } else {
                    return false;
                }
            } catch (IOException | JSONException e) {
                e.printStackTrace();
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean success) {
            if (success) {
                Log.e("登录状态: ", "登录成功！！！！！！！！！");
                // 登录成功，跳转到音乐播放器页面
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            } else {
                // 登录失败，显示错误信息或执行其他操作
                Toast.makeText(LoginActivity.this, "用户名或密码不正确!", Toast.LENGTH_SHORT).show();
            }
        }
    }
}